#include "../../common/dispatcher.hpp"
#include "../../server/rpc_router.hpp"


void Add(const Json::Value & req,Json::Value & rsp)
{
    int num1 = req["num1"].asInt();
    int num2 = req["num2"].asInt();
    rsp = num1+num2;
}

int main()
{
    std::shared_ptr<rpc::Dispatcher> dispatcher = std::make_shared<rpc::Dispatcher>();
    auto router = std::make_shared<rpc::server::RpcRouter>();//RpcRouter对象
    std::unique_ptr<rpc::server::SDescribeFactory> desc_factory(new rpc::server::SDescribeFactory());
    desc_factory->setMethodName("Add");
    desc_factory->setParamsDesc("num1",rpc::server::VType::INTEGRAL);
    desc_factory->setParamsDesc("num2",rpc::server::VType::INTEGRAL);
    desc_factory->setReturnType(rpc::server::VType::INTEGRAL);
    desc_factory->setCallback(Add);//设置method为Add的回调函数
    router->registerMethod(desc_factory->build());//注册服务

    auto cb = std::bind(&rpc::server::RpcRouter::onRpcRequest,router.get(),std::placeholders::_1,std::placeholders::_2);
    dispatcher->registerHandler<rpc::RpcRequest>(rpc::MType::REQ_RPC,cb);//将RpcRouter中的onRpcRequest方法注册进dispatcher
    //收到Rpc请求之后,就会进行调用RpcRouter中的onRpcRequest进行处理
    rpc::BaseServer::ptr server = rpc::ServerFactory::create(9090);
    rpc::MessageCallback message_cb = std::bind(&rpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);
    //server收到消息,调用dispatcher里面的onMessage方法,->dispatcher的onMessage方法再进行判断消息类型
    //RpcRequest则调用RpcRouter里面的onRpcRequest,onRpcRequest则调用用户设置的回调函数
    server->setMessageCallback(message_cb);
    server->start();
    return 0;
}

